package xdu.lz.stage7_jucCollection.a_list_skiplist;

/**
 * Created at 2019/10/28 0028 下午 8:18
 * 实现一个链表
 */
public class MyList {

    private static class Node{
        int val ;
        Node next;
        public Node(int val) {
            this.val = val;
        }
    }

    private int size;
    private Node frist;
    private Node tail;

    public MyList() {
        this.size = 0;
        this.frist = null;
        this.tail = frist;
    }


    public void addFirst(int e){
        Node newNode = new Node(e);
        if(frist != null){
            newNode.next = frist;
            frist = newNode;
        }else{
            frist = tail = newNode;
        }
        size ++;
    }

    public void addLast(int e){
        Node newNode = new Node(e);
        if(tail != null){
            tail.next = newNode;
            //update the tail
            tail = tail.next;
        }else{
            //the first element
            tail = newNode;
            frist = tail;
        }
        size ++;
    }

    public Integer pop(){
        return removeFirst();
    }
    public void push(int e){
        this.addFirst(e);
    }
    public Integer removeFirst(){
        if(frist == null){
            return null;
        }
        size -- ;
        int res = frist.val;
        frist = frist.next;
        return res;
    }
    public Integer removeLast(){
        if(tail == null){
            return null;
        }
        size -- ;
        int temp = tail.val;
        replaceTail();
        return temp;
    }

    private void replaceTail() {

        //only one node
        if(frist == tail){
            frist = tail = null;
            return;
        }
        //only two node
        if(frist.next == tail){
            tail = frist;
            frist.next = null;
            return;
        }
        Node cur = frist;
        while (cur.next.next != null){
            cur = cur.next;
        }
        tail = cur;
        // the pre tail
        cur.next  = null;
    }

    public int size(){
        return this.size;
    }
    public boolean isEmpty(){
        return this.size == 0;
    }

    public static void main(String[] args) {
        MyList list = new MyList();
        for (int i = 0; i < 10; i++) {
            list.push(i);
        }
        System.out.println("size = " + list.size);
        while (!list.isEmpty()){
            System.out.println(list.pop());
        }
    }
}
